<?php

namespace App\Recharge\Api;

use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Hengyixun extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $str = '/^[a-zA-Z]|_[a-zA-Z\d_-]{5,19}$/';
        if (preg_match($str, $bean->getAccount())) {
            $charge_account_type = '3';
        } else {
            $eg = '/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0-3,5-8])|(18[0-9])|166|198|199|191|195)\d{8}$/';
            $charge_account_type = preg_match($eg, $bean->getAccount()) ? '1' : '2';
        }
        $array = [
            'AppKey'            => $bean->getSupplierNum(),
            'TimesTamp'         => time(),
            'ProductCode'       => $bean->getGoodsId(), //商品编码
            'BuyCount'          => $bean->getRechargeNum() * $bean->getStartCharging(),
            'MOrderID'          => $bean->getOrderNo(),//订单号
            'ChargeAccount'     => $bean->getAccount(),
            'ChargeAccountType' => $charge_account_type,
            'CustomerIP'        => $bean->getIp(),
            'IsCallback'        => '1',
            'CallBackUrl'       => $bean->getNotifyUrl(), //异步回调地址
            'Version'           => '1.0',
        ];
        // sign
        $array['Sign'] = strtoupper(md5($array['AppKey'].$array['BuyCount'].$array['CallBackUrl'].$array['ChargeAccount']
            .$array['CustomerIP'].$array['MOrderID'].$array['ProductCode'].
            $array['TimesTamp'].$array['Version']. $bean->getSecretKey()));

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('State', '');
        $order_sn = $request->input('MOrderID', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['2', '3']))->setRechargeSuccess($status == '2');
    }
}
